"""
添加商品页面

用于添加新商品的页面
"""

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
from pathlib import Path
import sys

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))

from src.gui.main_app import BasePage
from src.gui.design_system import (DesignSystem, create_card_frame, 
                                  create_primary_button, create_secondary_button,
                                  create_success_button, create_danger_button)


class AddProductPage(BasePage):
    """添加商品页面"""
    
    def __init__(self, parent, app):
        super().__init__(parent, app)
        self.product_data = {}
        
    def create_page(self):
        """创建页面内容"""
        self.frame = ttk.Frame(self.parent)
        
        # 页面标题
        self.create_header()
        
        # 商品基本信息
        self.create_basic_info()
        
        # 商品详细信息
        self.create_detail_info()
        
        # 商品图片
        self.create_product_images()
        
        # 操作按钮
        self.create_action_buttons()
    
    def create_header(self):
        """创建页面标题"""
        header_frame = ttk.Frame(self.frame)
        header_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))
        
        # 标题区域
        title_container = ttk.Frame(header_frame)
        title_container.pack(side="left", fill="x", expand=True)
        
        title_label = ttk.Label(
            title_container,
            text="➕ 添加商品",
            style='Title.TLabel'
        )
        title_label.pack(side="left")
        
        # 副标题
        subtitle_label = ttk.Label(
            title_container,
            text="创建新的商品信息",
            style='Muted.TLabel'
        )
        subtitle_label.pack(side="left", padx=(DesignSystem.SPACING['md'], 0))
        
        # 返回按钮
        back_btn = create_secondary_button(
            header_frame,
            text="← 返回商品列表",
            command=lambda: self.app.show_page("product_list")
        )
        back_btn.pack(side="right")
    
    def create_basic_info(self):
        """创建基本信息区域"""
        basic_frame = create_card_frame(self.frame, "基本信息")
        basic_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))
        
        # 第一行：商品名称和SKU
        row1 = ttk.Frame(basic_frame)
        row1.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))
        
        # 商品名称
        name_frame = ttk.Frame(row1)
        name_frame.pack(side="left", fill="x", expand=True, padx=(0, DesignSystem.SPACING['lg']))
        
        ttk.Label(name_frame, text="商品名称:", style='Heading.TLabel').pack(anchor="w")
        self.product_name_var = tk.StringVar()
        name_entry = ttk.Entry(name_frame, textvariable=self.product_name_var, width=30)
        name_entry.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))
        
        # SKU编号
        sku_frame = ttk.Frame(row1)
        sku_frame.pack(side="right", fill="x", expand=True)
        
        ttk.Label(sku_frame, text="SKU编号:", style='Heading.TLabel').pack(anchor="w")
        self.product_sku_var = tk.StringVar()
        sku_entry = ttk.Entry(sku_frame, textvariable=self.product_sku_var, width=20)
        sku_entry.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))
        
        # 第二行：分类和品牌
        row2 = ttk.Frame(basic_frame)
        row2.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))
        
        # 商品分类
        category_frame = ttk.Frame(row2)
        category_frame.pack(side="left", fill="x", expand=True, padx=(0, DesignSystem.SPACING['lg']))
        
        ttk.Label(category_frame, text="商品分类:", style='Heading.TLabel').pack(anchor="w")
        self.product_category_var = tk.StringVar(value="请选择分类")
        category_combo = ttk.Combobox(
            category_frame,
            textvariable=self.product_category_var,
            values=["请选择分类", "👕 服装", "👟 鞋类", "👜 包包", "💄 美妆", "📱 数码", "🏠 家居"],
            state="readonly",
            width=27
        )
        category_combo.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))
        
        # 商品品牌
        brand_frame = ttk.Frame(row2)
        brand_frame.pack(side="right", fill="x", expand=True)
        
        ttk.Label(brand_frame, text="商品品牌:", style='Heading.TLabel').pack(anchor="w")
        self.product_brand_var = tk.StringVar()
        brand_entry = ttk.Entry(brand_frame, textvariable=self.product_brand_var, width=20)
        brand_entry.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))
        
        # 第三行：价格和状态
        row3 = ttk.Frame(basic_frame)
        row3.pack(fill="x")
        
        # 商品价格
        price_frame = ttk.Frame(row3)
        price_frame.pack(side="left", fill="x", expand=True, padx=(0, DesignSystem.SPACING['lg']))
        
        ttk.Label(price_frame, text="商品价格 (¥):", style='Heading.TLabel').pack(anchor="w")
        self.product_price_var = tk.StringVar()
        price_entry = ttk.Entry(price_frame, textvariable=self.product_price_var, width=15)
        price_entry.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))
        
        # 商品状态
        status_frame = ttk.Frame(row3)
        status_frame.pack(side="right", fill="x", expand=True)
        
        ttk.Label(status_frame, text="商品状态:", style='Heading.TLabel').pack(anchor="w")
        self.product_status_var = tk.StringVar(value="✅ 上架")
        status_combo = ttk.Combobox(
            status_frame,
            textvariable=self.product_status_var,
            values=["✅ 上架", "📦 备货中", "⏸️ 下架", "🔒 停产"],
            state="readonly",
            width=17
        )
        status_combo.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))
    
    def create_detail_info(self):
        """创建详细信息区域"""
        detail_frame = create_card_frame(self.frame, "详细信息")
        detail_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))
        
        # 商品描述
        desc_frame = ttk.Frame(detail_frame)
        desc_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))
        
        ttk.Label(desc_frame, text="商品描述:", style='Heading.TLabel').pack(anchor="w")
        
        # 文本框和滚动条
        text_container = ttk.Frame(desc_frame)
        text_container.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))
        
        self.product_desc_text = tk.Text(text_container, height=4, wrap=tk.WORD)
        desc_scrollbar = ttk.Scrollbar(text_container, orient="vertical", command=self.product_desc_text.yview)
        self.product_desc_text.configure(yscrollcommand=desc_scrollbar.set)
        
        self.product_desc_text.pack(side="left", fill="both", expand=True)
        desc_scrollbar.pack(side="right", fill="y")
        
        # 标签和关键词
        tags_frame = ttk.Frame(detail_frame)
        tags_frame.pack(fill="x")
        
        ttk.Label(tags_frame, text="商品标签 (用逗号分隔):", style='Heading.TLabel').pack(anchor="w")
        self.product_tags_var = tk.StringVar()
        tags_entry = ttk.Entry(tags_frame, textvariable=self.product_tags_var)
        tags_entry.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))
    
    def create_product_images(self):
        """创建商品图片区域"""
        image_frame = create_card_frame(self.frame, "商品图片")
        image_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))
        
        # 图片上传区域
        upload_container = ttk.Frame(image_frame)
        upload_container.pack(fill="x")
        
        # 主图上传
        main_image_frame = ttk.Frame(upload_container)
        main_image_frame.pack(side="left", fill="x", expand=True, padx=(0, DesignSystem.SPACING['lg']))
        
        ttk.Label(main_image_frame, text="主图:", style='Heading.TLabel').pack(anchor="w")
        
        main_upload_area = ttk.Frame(main_image_frame, relief="solid", borderwidth=1, padding=DesignSystem.SPACING['lg'])
        main_upload_area.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))
        
        ttk.Label(main_upload_area, text="🖼️", font=(DesignSystem.FONTS['family_primary'], 24)).pack()
        ttk.Label(main_upload_area, text="点击上传主图", style='Muted.TLabel').pack()
        
        main_upload_btn = create_secondary_button(
            main_upload_area,
            text="📂 选择图片",
            command=lambda: self.upload_image("main")
        )
        main_upload_btn.pack(pady=(DesignSystem.SPACING['sm'], 0))
        
        # 详情图上传
        detail_image_frame = ttk.Frame(upload_container)
        detail_image_frame.pack(side="right", fill="x", expand=True)
        
        ttk.Label(detail_image_frame, text="详情图:", style='Heading.TLabel').pack(anchor="w")
        
        detail_upload_area = ttk.Frame(detail_image_frame, relief="solid", borderwidth=1, padding=DesignSystem.SPACING['lg'])
        detail_upload_area.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))
        
        ttk.Label(detail_upload_area, text="🖼️", font=(DesignSystem.FONTS['family_primary'], 24)).pack()
        ttk.Label(detail_upload_area, text="点击上传详情图", style='Muted.TLabel').pack()
        
        detail_upload_btn = create_secondary_button(
            detail_upload_area,
            text="📂 选择图片",
            command=lambda: self.upload_image("detail")
        )
        detail_upload_btn.pack(pady=(DesignSystem.SPACING['sm'], 0))
    
    def create_action_buttons(self):
        """创建操作按钮"""
        button_frame = ttk.Frame(self.frame)
        button_frame.pack(fill="x", pady=DesignSystem.SPACING['xl'])
        
        # 左侧按钮
        left_frame = ttk.Frame(button_frame)
        left_frame.pack(side="left")
        
        preview_btn = create_secondary_button(
            left_frame,
            text="👁️ 预览",
            command=self.preview_product
        )
        preview_btn.pack(side="left", padx=(0, DesignSystem.SPACING['sm']))
        
        # 右侧按钮
        right_frame = ttk.Frame(button_frame)
        right_frame.pack(side="right")
        
        cancel_btn = create_secondary_button(
            right_frame,
            text="❌ 取消",
            command=self.cancel_add
        )
        cancel_btn.pack(side="right", padx=(DesignSystem.SPACING['sm'], 0))
        
        save_btn = create_success_button(
            right_frame,
            text="💾 保存商品",
            command=self.save_product
        )
        save_btn.pack(side="right")
    
    def upload_image(self, image_type):
        """上传图片"""
        file_types = [
            ("图片文件", "*.jpg *.jpeg *.png *.gif *.bmp"),
            ("所有文件", "*.*")
        ]
        
        file_path = filedialog.askopenfilename(
            title=f"选择{'主图' if image_type == 'main' else '详情图'}",
            filetypes=file_types
        )
        
        if file_path:
            messagebox.showinfo("成功", f"{'主图' if image_type == 'main' else '详情图'}上传成功！\n{file_path}")
    
    def preview_product(self):
        """预览商品"""
        if not self.product_name_var.get():
            messagebox.showwarning("提示", "请先填写商品名称")
            return
        
        preview_info = f"""
商品预览:

商品名称: {self.product_name_var.get()}
SKU编号: {self.product_sku_var.get()}
商品分类: {self.product_category_var.get()}
商品品牌: {self.product_brand_var.get()}
商品价格: ¥{self.product_price_var.get()}
商品状态: {self.product_status_var.get()}
商品标签: {self.product_tags_var.get()}

商品描述:
{self.product_desc_text.get('1.0', tk.END).strip()}
        """
        
        messagebox.showinfo("商品预览", preview_info.strip())
    
    def save_product(self):
        """保存商品"""
        # 验证必填字段
        if not self.product_name_var.get():
            messagebox.showwarning("提示", "请填写商品名称")
            return
        
        if not self.product_sku_var.get():
            messagebox.showwarning("提示", "请填写SKU编号")
            return
        
        if self.product_category_var.get() == "请选择分类":
            messagebox.showwarning("提示", "请选择商品分类")
            return
        
        # 收集商品数据
        self.product_data = {
            'name': self.product_name_var.get(),
            'sku': self.product_sku_var.get(),
            'category': self.product_category_var.get(),
            'brand': self.product_brand_var.get(),
            'price': self.product_price_var.get(),
            'status': self.product_status_var.get(),
            'description': self.product_desc_text.get('1.0', tk.END).strip(),
            'tags': self.product_tags_var.get()
        }
        
        messagebox.showinfo("成功", f"商品「{self.product_data['name']}」保存成功！")
        
        # 清空表单
        self.clear_form()
    
    def cancel_add(self):
        """取消添加"""
        if self.has_unsaved_changes():
            if messagebox.askyesno("确认", "有未保存的更改，确定要取消吗？"):
                self.app.show_page("product_list")
        else:
            self.app.show_page("product_list")
    
    def has_unsaved_changes(self):
        """检查是否有未保存的更改"""
        return (self.product_name_var.get() or 
                self.product_sku_var.get() or 
                self.product_brand_var.get() or
                self.product_price_var.get() or
                self.product_desc_text.get('1.0', tk.END).strip() or
                self.product_tags_var.get())
    
    def clear_form(self):
        """清空表单"""
        self.product_name_var.set("")
        self.product_sku_var.set("")
        self.product_category_var.set("请选择分类")
        self.product_brand_var.set("")
        self.product_price_var.set("")
        self.product_status_var.set("✅ 上架")
        self.product_desc_text.delete('1.0', tk.END)
        self.product_tags_var.set("")
